import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems :[],//购物车列表
  },
  getters: {
    cartTotal: state => {  
      return state.cartItems.reduce((total, item) => {  
        return total + item.price * item.quantity;  
      }, 0);  
    },  
  },
  mutations: {
    addToCart(state,item){
      const cartItem = state.cartItems.find( x => x.id == item.id);
      if(cartItem)
      {
        cartItem.quantity++;
      }
      else
      {
        state.cartItems.push({...item,quantity: 1});
      }
    },
    removeFromCart(state,itemid){
      const index = state.cartItems.findIndex(x => x.id == itemid);
      if(index > -1)
      {
        state.cartItems.splice(index,1);
      }
    }
  },
  actions: {
  },
  modules: {
  }
});
/*import Vue from 'vue';  
import Vuex from 'vuex';  
  
Vue.use(Vuex);  
  
export default new Vuex.Store({  
  state: {  
    cartItems: [], // 购物车商品列表  
  },  
  mutations: {  
    addToCart(state, item) {  
      const cartItem = state.cartItems.find(x => x.id === item.id);  
      if (cartItem) {  
        cartItem.quantity++;  
      } else {  
        state.cartItems.push({ ...item, quantity: 1 });  
      }  
    },  
    removeFromCart(state, itemId) {  
      const index = state.cartItems.findIndex(x => x.id === itemId);  
      if (index > -1) {  
        state.cartItems.splice(index, 1);  
      }  
    },  
  },  
  getters: {  
    cartTotal: state => {  
      return state.cartItems.reduce((total, item) => {  
        return total + item.price * item.quantity;  
      }, 0);  
    },  
  },  
});*/